<template>
  <!-- SignInPage 签到 -->
  <PageContainer>
    <Loading v-model="loading">
      <view class="container">
        <Header title="签到" />
        <!-- <view class="page-title">请在下方签名完成签到</view>
        <view class="signature-area" @click.capture="toSign">
          <image v-if="signUrl.tmpUrl" :src="signUrl.tmpUrl" />
          <TButton v-else text="点击绘制签名区" type="primary" />
        </view> -->
        <!-- <TButtonGroup>
          <TButton
            class="gutter-btn"
            text="提交&领取参会证"
            type="primary"
            :disabled="!signUrl.imgUrl"
            customClass="br-50"
            @click="submit"
          />
        </TButtonGroup> -->
      </view>
    </Loading>
    <ShowModal
      v-model="isShowModal"
      :isMaskClick="false"
      title="您暂未报名活动"
      content="如果您已报名或代他人参加活动请联系现场工作人员签到。"
      cancel-text="返回首页"
      cancel-color="#999996"
      confirm-text="立即报名"
      confirm-color="#2878FF"
      :show-confirm="!!data?.enrollSign"
      @close="navigateBack"
      @confirm="toSignUp"
    />
  </PageContainer>
</template>

<script lang="ts" setup>
  /**  SignInPage  签到 */
  import PageContainer from '@/components/PageContainer/index.vue';
  import Header from '@/components/Header/index.vue';
  import { reactive, ref, unref } from 'vue';
  import { reLaunch, switchTab, onLoad, redirectTo, navigateBack } from '@/router';
  import Loading from '@/components/Loading/index.vue';
  import { registrationStatus } from '@/api/activity';
  import type { IRegistrationStatusRes } from '@/api/activity/types';
  import { isLogin } from '@/utils/is';
  import ShowModal from '@/components/ShowModal/index.vue';
  import {
    ActivityStatusEnum,
    ApprovalStatusEnum,
    EnrollVerifyEnum,
  } from '@/enums/activityStatusEnum';
  import { TabbarPageEnum } from '@/enums/pageEnum';
  import { Toast } from '@/utils';
  import { type SignInPage } from '@/router/types/modules';
  import { onHide, onShow } from '@dcloudio/uni-app';
  import { useUserStoreWithOut } from '@/store/modules/user';
  import { toSelectiveType } from '@/utils/dynamicConfig';
  import { useActivityStore } from '@/store/modules/activity';
  import { toActivityRegistration } from '../utils';

  const { currentCocId } = useUserStoreWithOut();
  const { setActivityOrderRouteParams } = useActivityStore();

  const loading = ref(true);
  const data = ref<IRegistrationStatusRes>();
  const activityId = ref();
  const equipmentNumber = ref<string>();
  const options = ref<SignInPage>();
  const isInit = ref(false);
  const isShowModal = ref(false);

  /**
   * 小程序码 参数
   * scene {string} 活动id
   */
  onLoad<'SignInPage'>((op) => {
    options.value = op;
    isLogin(() => {
      isInit.value = false;
      __init(op);
    }, true);
  });

  onShow(() => {
    if (unref(isInit) && options.value) {
      __init(options.value);
      isInit.value = false;
    }
  });

  onHide(() => {
    isInit.value = true;
  });

  function __init(op: SignInPage) {
    activityId.value = op.scene;
    equipmentNumber.value = op.equipmentNumber;
    op.scene &&
      registrationStatus(op.scene)
        .then((r) => {
          data.value = r;
          const status = r.activityStatus;
          /** 1. 验证活动是否开始 */
          switch (status) {
            case ActivityStatusEnum.START:
            case ActivityStatusEnum.REGISTRATION_UNDERWAY:
            case ActivityStatusEnum.REGISTRATION_END:
              verifyRegistrationStatus();
              break;
            case ActivityStatusEnum.END:
            case ActivityStatusEnum.CANCEL:
              endTast('活动已结束, 请联系主办方');
              break;

            default:
              endTast('活动暂未开始');
              break;
          }
        })
        .catch((err) => console.log(err));
  }

  /** 2. 验证报名状态 */
  function verifyRegistrationStatus() {
    if (!data.value) return;
    const { approvalStatus, signIn, isOtherSign, activityId } = data.value;
    switch (approvalStatus) {
      case null:
      case ApprovalStatusEnum.REJECT:
        setActivityOrderRouteParams(data.value.activityVo);
        /** 去报名 */
        if (isOtherSign) {
          reLaunch({
            name: 'selfRegistration',
            options: {
              activityId,
              equipmentNumber: unref(equipmentNumber) as string,
            },
          });
          return;
        }
        isShowModal.value = true;
        // endTast('本次活动未报名,不能扫码签到');
        break;
      case ApprovalStatusEnum.UNDERREVIEW:
        /** 报名审核中 */
        reLaunch({
          name: 'registrationUnderReview',
          options: {
            activityId: data.value?.activityId as number,
            equipmentNumber: unref(equipmentNumber),
          },
        });
        break;
      case ApprovalStatusEnum.PASSED:
        if (signIn) {
          toSignInResult();
        } else {
          /** 去签名 */
          verifySignStatus();
        }
        break;
      case ApprovalStatusEnum.NOTPASS:
        endTast('审核未通过');
        break;
    }
  }

  function toSignUp() {
    if (!data.value) return;
    const { memberOpen } = data.value;

    if (currentCocId || memberOpen) {
      toActivityRegistration({
        data: data.value.activityVo,
        shareKey: void 0,
        isVerifyNumber: false,
        routerScene: 'signIn',
        equipmentNumber: equipmentNumber.value
      });
      // reLaunch({
      //   name: 'activityDetails',
      //   options: {
      //     id: activityId,
      //   },
      // });

      return;
    }

    uni.showModal({
      title: '提示',
      content: '此活动仅向会员开放,您无报名权限',
      showCancel: false,
      confirmText: '立即入会',
      success: () => {
        toSelectiveType(
          {
            linkUrl: 'selectiveType',
            isRedirectTo: true,
          },
          () => {},
          true,
        );
      },
    });
  }

  /** 3.验证是否要签名 */
  function verifySignStatus() {
    if (data.value?.manualSign) {
      // loading.value = false;
      toSign();
    } else {
      toSignInResult();
    }
  }

  function toSignInResult(url?: string) {
    if (data.value) {
      reLaunch({
        name: 'signInResult',
        options: {
          activityId: data.value.activityId,
          url,
          equipmentNumber: unref(equipmentNumber) as string,
        },
      });
    }
  }

  function endTast(title: string) {
    const duration = 1500;
    return Toast(
      {
        title,
        success: () => setTimeout(() => switchTab(TabbarPageEnum.BASE_HOME), duration),
      },
      undefined,
      duration,
    );
  }

  /** 跳转电子签名功能 */
  const signUrl = reactive({
    tmpUrl: '',
    imgUrl: '',
  });

  function toSign() {
    if (!data.value) return;
    reLaunch({
      name: 'activitySign',
      options: {
        activityId: data.value.activityId,
        equipmentNumber: unref(equipmentNumber) as string,
      },
    });
  }

  /** 报名完成 */
  function registrationFinish() {
    if (!data.value) return;
    if (data.value.enrollVerify == EnrollVerifyEnum.YES) {
      reLaunch({
        name: 'registrationUnderReview',
        options: {
          activityId: data.value.activityId,
          equipmentNumber: unref(equipmentNumber) as string,
        },
      });
    } else {
      verifySignStatus();
    }
  }

  function submit() {
    const url = signUrl.imgUrl;
    if (!data.value) return;
    redirectTo({
      name: 'signInResult',
      options: {
        activityId: data.value.activityId,
        url,
        equipmentNumber: unref(equipmentNumber) as string,
      },
    });
  }
</script>
<style lang="scss" scoped>
  .container {
    width: calc(100vw - 60rpx);
    height: calc(100vh - 60rpx);
    background-color: #fff;
    padding: 30rpx;
    .page-title {
      font-size: 35rpx;
      color: #333;
      font-weight: bolder;
      margin: 40rpx 0;
    }
    .signature-area {
      width: 700rpx;
      height: 322rpx;
      background: #f5f5f5;
      border-radius: 10rpx;
      border: 1px dashed #707070;
      color: #aaabab;
      font-size: 31rpx;
      display: flex;
      align-items: center;
      justify-content: center;
      > image {
        width: 100%;
        height: 100%;
      }
    }
  }
</style>
